﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace GPU_Performance_Manager
{
    internal static class WindowsHotKeyConstants
    {
        // Modifiers
        public const int NOMOD = 0x0000;
        public const int ALT = 0x0001;
        public const int CTRL = 0x0002;
        public const int SHIFT = 0x0004;
        public const int WIN = 0x0008;

        // Windows message ID for hotkey
        public const int WM_HOTKEY_MSG_ID = 0x0312;
    }

    internal class GlobalHotKey
    {
        private IntPtr hWnd;
        private int id;
        private int modifiers;
        private int key;
        private bool registered;
        private Keys keyData;

        public int ID { get { return id; } }

        public Keys KeyData { get { return keyData; } }

        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        internal GlobalHotKey(Form form, Keys keyData)
        {
            this.keyData = keyData;
            key = (int)keyData & (int)Keys.KeyCode;
            modifiers = 0;
            if ((keyData & Keys.Control) == Keys.Control)
                modifiers = modifiers | WindowsHotKeyConstants.CTRL;
            if ((keyData & Keys.Alt) == Keys.Alt)
                modifiers = modifiers | WindowsHotKeyConstants.ALT;
            if ((keyData & Keys.Shift) == Keys.Shift)
                modifiers = modifiers | WindowsHotKeyConstants.SHIFT;

            hWnd = form.Handle;
            id = this.GetHashCode();
            registered = false;
        }

        ~GlobalHotKey()
        {
            Unregister();
        }

        public override int GetHashCode()
        {
            return modifiers ^ key ^ hWnd.ToInt32();
        }

        public bool Register()
        {
            if (registered == false)
            {
                if (RegisterHotKey(hWnd, id, modifiers, key) == true)
                {
                    registered = true;
                    return true;
                }
                else
                    return false;
            }
            else
                return true;
        }

        public bool Unregister()
        {
            if (registered == true)
            {
                if (UnregisterHotKey(hWnd, id) == true)
                {
                    registered = false;
                    return true;
                }
                else
                    return false;
            }
            else
                return true;
        }
    }
}
